/**
 * Created by liyang on 2017/10/16.
 */
var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs"),
    port = 8000,
    News = require('./news.js');
var indexHttp = 0;
console.log(News);
const news = new News();
function openServer(port) {
    http.createServer(function(req, res) {
        if (req.url == '/api') {
            console.log('又来')
            news.getNew(req, res);
            return;
        }
        var pathname = __dirname + url.parse(req.url).pathname;
        if (path.extname(pathname) == "") {
            pathname += "/";
        }
        if (pathname.charAt(pathname.length - 1) == "/") {
            pathname += "index.html";
            indexHttp++;
            console.log(indexHttp+ '���ʵ�ַ��' +req.connection.remoteAddress + '����˿ڣ�' +port);
        }
        if (path.isAbsolute(pathname)) {
            switch (path.extname(pathname)) {
                case ".html":
                    res.writeHead(200, {
                        "Content-Type": "text/html"
                    });
//              indexHttp ++
                    break;
                case ".js":
                    res.writeHead(200, {
                        "Content-Type": "text/javascript"
                    });
                    break;
                case ".css":
                    res.writeHead(200, {
                        "Content-Type": "text/css"
                    });
                    break;
                case ".gif":
                    res.writeHead(200, {
                        "Content-Type": "image/gif"
                    });
                    break;
                case ".jpg":
                    res.writeHead(200, {
                        "Content-Type": "image/jpeg"
                    });
                    break;
                case ".png":
                    res.writeHead(200, {
                        "Content-Type": "image/png"
                    });
                    break;
                default:
                    res.writeHead(200, {
                        "Content-Type": "application/octet-stream"
                    });
            }

            fs.readFile(pathname, function(err, data) {
                res.end(data);
            });
        } else {
            res.writeHead(404, {
                "Content-Type": "text/html"
            });
            res.end("<h1>404 Not Found</h1>");
        }
    }).listen(port);
    console.log("Server running/" + port);
}
openServer(port++);